package person.bing.fbcloud.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import person.bing.fbcloud.SysUserInfoVo;
import person.bing.fbcloud.entity.SysMenu;
import person.bing.fbcloud.entity.SysRole;
import person.bing.fbcloud.entity.SysRoleMenu;
import person.bing.fbcloud.entity.SysUser;
import person.bing.fbcloud.mapper.SysUserMapper;
import person.bing.fbcloud.service.SysMenuService;
import person.bing.fbcloud.service.SysRoleMenuService;
import person.bing.fbcloud.service.SysRoleService;
import person.bing.fbcloud.service.SysUserService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author mengfb
 * @since 2020-03-16
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysMenuService sysMenuService;


    @Override
    public SysUserInfoVo getUserInfoByName(String userName) {
        SysUserInfoVo sysUserInfoVo = new SysUserInfoVo();
        SysUser sysUser = this.getOne(Wrappers.<SysUser>query().lambda()
                .eq(SysUser::getUserName, userName)
        );
        if (ObjectUtil.isNotNull(sysUser)){
            sysUser.setCreateTime(null);
            sysUser.setUpdateTime(null);
            sysUser.setId(null);
            sysUser.setStatu(null);
            sysUserInfoVo.setSysUser(sysUser);
            String roleKey = sysUser.getRoleKey();
            List<SysRoleMenu> sysRoleMenuList = sysRoleMenuService.list(Wrappers.<SysRoleMenu>query().lambda()
                    .eq(SysRoleMenu::getRoleKey, roleKey)
            );
            if (CollectionUtil.isNotEmpty(sysRoleMenuList)) {
                List<String> menuKeyList = sysRoleMenuList.stream().map(SysRoleMenu::getMenuKey).collect(Collectors.toList());
                List<SysMenu> sysMenuList = sysMenuService.list(Wrappers.<SysMenu>query().lambda()
                        .in(SysMenu::getMenuKey, menuKeyList)
                );
                if (CollectionUtil.isNotEmpty(sysMenuList)) {
                    List<String> permissionList = sysMenuList.stream().map(SysMenu::getPermission).collect(Collectors.toList());
                    sysUserInfoVo.setPermissions(permissionList);
                }
            }
        }
        return sysUserInfoVo;
    }
}
